

#include "unity.h"
#include "unity_fixture.h"

#include "log/log2.h"
#include "BSP_Sleep.h"

#include <phApp_Init.h>
#include <Reader/Reader.h>
#include <Reader/ReaderISO14443.h>

#include "reader_cfg.h"
#include "config/zkcfg.h"

#define LISTEN_PHASE_TIME_MS		10

/*===================================================================*/
/*===================================================================*/
static void reader_zkcfg_key_data_dbg(const zkcfg_key_data_t* kdata){
	LOG2_PRINT("\r\n key data: \n");
	LOG2_PRINT("\tkid: %d\n", kdata->kid);
	LOG2_PRINT("\ttype: %d\n", kdata->type);
	LOG2_PRINT("\tlength: %d\n", kdata->length);
	LOG2_PRINT("\tkeys:");
	LOG2_DUMP_HEX(kdata->key, kdata->length);
	LOG2_PRINT("\r\n");
}

static void reader_zkcfg_keyset_dbg(const zkcfg_keyset_t* ks){
	LOG2_PRINT("\r\n key set: \n");
	LOG2_PRINT("\taid: %06X\n", ks->aid);
	LOG2_PRINT("\tapp: %d\n", ks->app);
	LOG2_PRINT("\tkey_id: %d\n", ks->key_id);
	LOG2_PRINT("\tkey_type %d\n", ks->key_type);
	LOG2_PRINT("\tkey_num: %d\n", ks->key_num);
	LOG2_PRINT("\tdiversified: %d\n", ks->diversified);
	LOG2_PRINT("\r\n");
}

TEST_GROUP(ConfigCard);


TEST_SETUP(ConfigCard)
{
	reader.hfFlags = TAG_MASK_MIFARE;
	Reader_NFC_LoadProfile(reader.hfFlags, 0, 0, 0);
}

TEST_TEAR_DOWN(ConfigCard)
{
	Reader_NFC_RfOff();
}



TEST(ConfigCard, read)
{
	SimpleTag_T simpleTag;
	int ret;
	while(1){
		Reader_NFC_RfOff();
		BSP_Sleep_Ms(500);
		ret = Reader_NFC_Discovery2(&simpleTag, 0);
		if(ret){
			continue;
		}
		uint8_t ats[64];
		uint8_t alen;
		ret = Reader_ISO14443A_GetATS(ats, &alen);
		if(ret){
			LOG2_ERR("ats error!");
			continue;
		}
		LOG2_BUF_DBG("ats", ats, alen);
		ret = reader_zkcfg_read(simpleTag.uid);
		if(ret){
			LOG2_ERR("zkcfg read fail: %d", ret);
			continue;
		}
		
		zkcfg_keys_t keys;
		ret = zkcfg_read_keys(&keys);
		if(ret){
			LOG2_ERR("read keys fail: %d", ret);
		}
		else{
			zkcfg_key_data_t* kd = &keys.privacy;
			for(int i = 0; i < 2; i++){
				reader_zkcfg_key_data_dbg(&kd[i]);
			}
		}
		
		zkcfg_keyset_t keyset[2];
		ret = zkcfg_read(ZKCFG_PAGE_CFG, 0, sizeof(keyset), keyset);
		if(ret){
			LOG2_ERR("read cfg fail: %d", ret);
		}
		else{
			for(int i = 0; i < 2; i++){
				reader_zkcfg_keyset_dbg(&keyset[i]);
			}
		}
		
		uint8_t rkey[16];
		ret = zkcfg_read(ZKCFG_PAGE_MANU, 0, 16, rkey);
		if(ret){
			LOG2_ERR("read rkey fail: %d", ret);
		}
		else{
			LOG2_PRINT("rkey: ");
			LOG2_DUMP_HEX(rkey, 16);
		}
	}
}


